<?php


namespace app\controller\api;


use app\BaseController;
use app\common\OrderStatus;
use app\models\config\ConfigModel;
use app\models\goods\GoodsCartModel;
use app\models\goods\GoodsModel;
use app\models\goods\GoodsSkuModel;
use app\models\order\OrderDetailModel;
use app\models\order\OrderModel;
use app\models\shop\ShopModel;
use app\models\user\UserAddressModel;
use app\models\user\UserLevelModel;
use app\models\user\UserModel;
use app\services\config\ConfigService;
use app\services\order\CouponService;
use app\services\order\OrderService;
use app\services\user\DetailedGreenScoresService;
use app\services\user\DetailIntegralService;
use app\services\user\DetailMoneyService;
use app\services\utils\QrcodeService;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

use app\models\order\OrderEvaluationModel;


use app\services\pay\PayService;
use app\strategy\pay\AliPay;
use app\services\goods\GoodsService;

class OrderController extends BaseController
{

    /**
     * 取消订单
     * @return \think\response\Json
     */
    public function cancelOrder()
    {
        try {
            $id = $this->request->param('id');
            $order = OrderModel::find($id);
            if(!$order){
                throw new \Exception('订单不存在！');
            }
            if($order['order_status'] != 1 && $order['order_status'] != 2){
                throw new \Exception('当前状态无法取消订单！');
            }

            if($order['order_status'] == 2){
                if($order['pay_typey'] == 2){
                    $strategy = new AliPay();
                    $service = new PayService();
                    $service->setStrategy($strategy);
                    $service->refund($id, '订单取消');
                }elseif($order['pay_type'] == 3){
                    //消费积分 余额
                    $type = DetailMoneyService::ORDER_REFUND;
                    DetailMoneyService::create($order['user_id'],$type,$order['order_balance'],$order['order_sn']);

                    $type = DetailIntegralService::RETURN;
                    DetailIntegralService::create($order['user_id'],$type,$order['order_integral'],$order['order_sn']);
                }elseif($order['pay_type'] == 4){
                    //余额返回账户
                   //修改用户余额
                   $type = DetailMoneyService::ORDER_REFUND;
                   DetailMoneyService::create($order['user_id'],$type,$order['pay_amount'],$order['order_sn']);
                }else{
                   throw new \Exception('当前支付状态无法取消订单！');
               }

                //减少用户的绿色积分
                $type = DetailedGreenScoresService::REDEMPTION;
                DetailedGreenScoresService::create($order['user_id'],$type,$order['green_scores'],$order['order_sn']);
            }

            OrderModel::where(['id' => $id, 'user_id' => $this->request->userId])->update(['order_status' => 0]);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取店铺列表
     * @return \think\response\Json
     */
    public function getShopList()
    {
        try {
            $list = Db::name('shop')->field('id,address,shop_name,img')->where('status', 1)->select()->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getShoppingCart()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            if (is_array($data) && $data) {
                GoodsCartModel::create([
                    'user_id' => $this->request->userId,
                    'goods_id' => $data['goods_id'],
                    'goods_sku_id' => $data['goods_sku_id'],
                    'num' => $data['num'],
                ]);
            }
            $list = GoodsCartModel::where('user_id', $this->request->userId)
                ->field('id,goods_id,goods_sku_id,num')
                ->select()
                ->each(function ($item) {
                    $item['goods_info'] = GoodsModel::where('id', $item['goods_id'])->field('id,name,image')->find();
                    $sku = GoodsSkuModel::where('id', $item['goods_sku_id'])->find();
                    if ($sku) {
                        $item['goods_sku_name'] = $sku['name'];
                        $item['sell_price'] = $sku['sell_price'];
                    }
                    return $item;
                });
            Db::commit();
            return $this->success($list);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function delShoppingCart()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            GoodsCartModel::destroy($id);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 订单列表
     * @return \think\response\Json
     */
    public function getOrderList()
    {
        try {
            $type = $this->request->param('type', 0);
            $where = $whereOr = [];
            $where[] = ['is_del', '=', 0];
            $userId = $this->request->userId;
//            $userId = 451;
            $page = $this->page;
            $limit = $this->limit;
            $where[] = ['user_id', '=', $userId];
            //$where[] = ['user_id', '=', 414];
            if ($type == 0) {
                // 全部
                $where[] = ['order_status', 'in', [1, 2, 3,4,7]];
            } elseif ($type == 1) {
                // 待付款
                $where[] = ['order_status', '=', 1];
            } elseif ($type == 2) {
                // 待发货
                $where[] = ['order_status', '=', 2];
            } elseif ($type == 4){
                //待完成
                $where[] = ['order_status', '=', 4];
            } elseif($type == 7){
                //待售后
                //$where[] = ['order_status', '=', 7];
                $where[] = ['order_status', 'in', [7,8]];
            } elseif ($type == 3) {
                //已发货
                $where[] = ['order_status', '=', 3];
            }elseif ($type == 5) {
                $where[] = ['order_status', '=', 5];
            }elseif ($type == 6) {
                $where[] = ['order_status', '=', 6];
            }
//            } elseif($type == 8){
//                //售后完成
//                $where[] = ['order_status', '=', 8];
//            }

            $list = OrderModel::where($where)
                ->field('id,type,order_sn,order_type,pay_type,pay_amount,create_time,order_status,after_sales_type,after_sales_time,after_sales_status')
                ->order('id', 'desc')
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->each(function ($item) {
                    $item['detail'] = OrderDetailModel::where('order_sn', $item['order_sn'])->field('id,goods_name,goods_price,goods_image,num')->select();

                    if($item['shop'] == 0){
                        $item['shop_name'] = ConfigService::getConfigValue('shop_name');
                        $item['shop_img'] = ConfigService::getConfigValue('shop_logo');
                    }else{
                        $shopinfo = ShopModel::where('id', $item['shop_id'])->find();
                        $item['shop_name'] = $shopinfo['shop_name'];
                        $item['shop_img'] = $shopinfo['img'];
                    }

                    return $item;
                })->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 订单详情
     * @return \think\response\Json
     */
    public function getOrderDetail()
    {
        try {
            $order_sn = $this->request->param('order_sn');
            $where[] = ['is_del', '=', 0];
            $where[] = ['user_id', '=', $this->request->userId];
            //$where[] = ['user_id', '=', 414];
            $where[] = ['order_sn', '=', $order_sn];
            $data = OrderModel::where($where)
                ->field('id,type,order_sn,pay_type,shop_id,address_id,order_type,pay_amount,create_time,delivery_time,grade_discount,coupon_amount,freight,order_status,is_evaluation')
                ->order('id', 'desc')
                ->find();
            if (!$data) {
                throw new \Exception('订单不存在');
            }
            $data['detail'] = OrderDetailModel::where('order_sn', $data['order_sn'])->field('id,goods_sku_id,goods_name,goods_price,goods_image,num')
                ->select()
                ->each(function ($item) {
                    $item['goods_sku_name'] = GoodsSkuModel::where('id', $item['goods_sku_id'])->value('name');
                    return $item;
                });

            if(intval($data['shop_id']) == 0){
                $data['shop_name'] = '自营';
                $data['shop_img'] = ConfigService::getConfigValue('logo');;
            }else{
                $shop_info = ShopModel::where('id', $data['shop_id'])->find();
                $data['shop_name'] = $shop_info['shop_name'];
                $data['shop_img'] = $shop_info['img'];
            }
            $data['address_info'] = UserAddressModel::where('id', $data['address_id'])->find();

            if($data['is_evaluation'] == 1){
                $data['evaluation'] = Db::name('order_evaluation')->where('order_id',$data['id'])->where('user_id',$this->request->userId)->value('evaluation');
            }else{
                $data['evaluation'] = '';
            }


            return $this->success($data);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 提货
     */
//    public function getBuyUserPaymentInfo()
//    {
//        Db::startTrans();
//        try {
//            $orderSn = $this->request->param('order_sn');
//            $orderInfo = Db::name('order')->where('order_sn', $orderSn)->find();
//            if (!$orderInfo) {
//                throw new \Exception("订单不存在");
//            }
//            Db::name('order')->where('order_sn', $orderSn)->update([
//                'order_status' => OrderStatus::APPLY_GET_GOODS,
//                'update_time' => date('Y-m-d H:i:s'),
//            ]);
//            $addressInfo = Db::name('user_address')->where('user_id', $orderInfo['user_id'])->find();
//            if (!$addressInfo) {
//                throw new \Exception("请设置提货地址");
//            }
//            $productInfo = Db::name('goods')->where('id', $orderInfo['goods_id'])->where('status', 1)->find();
//            if (!$productInfo) {
//                throw new \Exception("商品信息不存在");
//            }
//            Db::name('order_pick')->insert([
//                'paint_id' => $this->request->paintId,
//                'user_id' => $orderInfo['user_id'],
//                'goods_id' => $orderInfo['goods_id'],
//                'address_id' => $addressInfo['id'],
//                'order_sn' => $orderSn,
//                'order_status' => 1,
//                'goods_name' => $productInfo['name'],
//                'goods_img' => $productInfo['image'],
//                'goods_price' => $productInfo['price'],
//                'user_name' => $addressInfo['user_name'],
//                'user_phone' => $addressInfo['phone'],
//                'user_address' => $addressInfo['full_address'],
//                'create_time' => time(),
//                'update_time' => time(),
//            ]);
//            Db::commit();
//            return $this->success('', '提货成功');
//        } catch (\Exception $exception) {
//            Db::rollback();
//            return $this->error($exception->getMessage());
//        }
//    }

    /**
     * 申请上架
     */
//    public function applyOnline()
//    {
//        try {
//            $orderSn = $this->request->param('order_sn');
//            $orderInfo = Db::name('order')->where('order_sn', $orderSn)->find();
//            if (!$orderInfo) {
//                throw new \Exception("订单不存在");
//            }
//            if ($orderInfo['is_apply_online'] == 1) {
//                throw new \Exception("请勿重复申请上架");
//            }
//            Db::name('order')->where('order_sn', $orderSn)->update([
//                'is_apply_online' => 1,
//                'apply_online_time' => date('Y-m-d H:i:s'),
//                'update_time' => date('Y-m-d H:i:s'),
//            ]);
//            return $this->success();
//        } catch (\Exception $exception) {
//            return $this->error($exception->getMessage());
//        }
//    }

    /**
     * 匹配
     */
//    public function match()
//    {
//        Db::startTrans();
//        try {
//            $orderSn = $this->request->param('order_sn');
//            $orderInfo = Db::name('order')->where('order_sn', $orderSn)->find();
//            if (!$orderInfo) {
//                throw new \Exception("订单号错误");
//            }
//            if ($orderInfo['status'] != 0) {
//                throw new \Exception("订单还未上架");
//            }
//            $appointUid = $this->request->param('appoint_user_id');
//            $userInfo = Db::name('user')->where('id', $appointUid)->find();
//            if (!$userInfo) {
//                throw new \Exception("预约人不存在");
//            }
//            Db::name('order')->where('order_sn', $orderInfo['id'])->update([
//                'buy_user_id' => $appointUid,
//                'order_status' => 1,
//                'update_time' => time(),
//            ]);
//            Db::name('order')->where('order_sn', $orderInfo['old_order_sn'])->update([
//                'order_status' => 4,
//                'sell_time' => time(),
//                'update_time' => time(),
//            ]);
//            Db::commit();
//            return $this->success();
//        } catch (\Exception $exception) {
//            Db::rollback();
//            return $this->error($exception->getMessage());
//        }
//    }

    /**
     * 确认
     */
    public function confirm()
    {
        Db::startTrans();
        try {
            $orderSn = $this->request->param('order_sn');
            $service = new OrderService();
            $service->confirmOrder($orderSn);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            Log::error($exception->getMessage());
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 我已付款
     * @return \think\response\Json
     */
    public function hasPay()
    {
        Db::startTrans();
        try {
            $orderSn = $this->request->param('order_sn');
            $service = new OrderService();
            $service->hasPayOrder($orderSn);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            Log::error($exception->getMessage());
            return $this->error($exception->getMessage());
        }
    }

//    积分兑换
    public function redemptionPoints()
    {
        Db::startTrans();
        try {
            $orderSn = createOrderSn();
            $order = new OrderModel();
            $user = UserModel::find($this->request->userId);
            $pointsmall_id = $this->request->param('pointsmall_id');
            $num = $this->request->param('num');

            $goods = Db::name('pointsmall')->where('id', $pointsmall_id)->find();
            if (!$goods) {
                throw new \Exception('积分商品不存在');
            }
            $total_integral = bcmul($goods['integral'], $num, 2);
            if ($user['integral'] < $total_integral) {
                throw new \Exception('账户积分不足,无法兑换');
            }

            $order->order_sn = $orderSn;
            $order->type = 2; // 1-普通商品 2-积分兑换
            $order->pay_type = $this->request->param('pay_type');
            $order->order_type = $this->request->param('order_type'); //1-门店自提 2-送货上门
            if ($order->order_type == 1) {
                $order->shop_id = $this->request->param('shop_id');
                $shop = ShopModel::find($order->shop_id);
                if (!$shop) {
                    throw new \Exception('店铺不存在');
                }
            } else {
                $order->address_id = $this->request->param('address_id');
                $address = UserAddressModel::where('id', $order->address_id)->find();
                if (!$order->address_id) {
                    throw new \Exception('地址不存在');
                }
                $order->delivery_time = $this->request->param('delivery_time');
                $order->username = $address['username'];
                $order->user_mobile = $address['mobile'];
                $order->address_detail = $address['full_address'];
            }
            //订单积分
            $order->total_amount = $total_integral;
            $order->pay_amount = $order->total_amount;
            $order->user_id = $this->request->userId;
            $order->order_status = 1;
            $order->pointsmall_id = $pointsmall_id;
            $order->save();

            if($order->order_type == 1){
                //门店自提 直接扣除积分
                $order->order_status = 2;
            }else{
                //送货上门 需要支付运费
                $order->order_status = 1;
            }
            //扣除积分
            $type = DetailIntegralService::REDEMPTION;
            DetailIntegralService::create($user['id'],$type,$order->total_amount,$orderSn);
            $order->save();
            OrderDetailModel::create([
                'order_sn' => $orderSn,
                'pointsmall_id' => $pointsmall_id,
                'goods_name' => $goods['name'],
                'goods_sku_id' => '',
                'goods_price' => $goods['integral'],
                'num' => $num,
                'goods_image' => $goods['image'],
            ]);
            Db::commit();
            return $this->success(['order_sn' => $orderSn],'订单创建成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 创建订单
     * @return \think\response\Json
     */
    public function createOrder()
    {
        Db::startTrans();
        try {
            $orderSn = createOrderSn();
            $order = new OrderModel();
            $user = UserModel::find($this->request->userId);
            $type = $this->request->param('type');
            if ($type == 1) {
                //商品购买
                $goods_id = $this->request->param('goods_id');
                $goods = GoodsModel::find($goods_id);
                if (!$goods) {
                    throw new \Exception('商品不存在');
                }
                if ($goods['status'] != 1) {
                    throw new \Exception('商品已下架');
                }
                $goods_sku_id = $this->request->param('goods_sku_id');
                $goods_sku = GoodsSkuModel::find($goods_sku_id);
                if (!$goods_sku) {
                    throw new \Exception('规格不存在');
                }
            } else {
                //积分兑换
                $pointsmall_id = $this->request->param('pointsmall_id');
                $goods = Db::name('pointsmall')->where('id', $pointsmall_id)->find();
                if (!$goods) {
                    throw new \Exception('积分商品不存在');
                }
                if ($user['integral'] < $goods['integral']) {
                    throw new \Exception('账户积分不足,无法兑换');
                }
            }

            $num = $this->request->param('num');
            $order->order_sn = $orderSn;
            $order->type = $type; // 1-普通商品 2-积分兑换
            $order->coupon_id = $this->request->param('coupon_id');
            $order->pay_type = $this->request->param('pay_type');
            $order->order_type = $this->request->param('order_type');
            if ($order->order_type == 1) {
                $order->shop_id = $this->request->param('shop_id');
                $shop = ShopModel::find($order->shop_id);
                if (!$shop) {
                    throw new \Exception('店铺不存在');
                }
            } else {
                $order->address_id = $this->request->param('address_id');
                $address = UserAddressModel::where('id', $order->address_id)->find();
                if (!$order->address_id) {
                    throw new \Exception('地址不存在');
                }
                $order->delivery_time = $this->request->param('delivery_time');
                $order->username = $address['username'];
                $order->user_mobile = $address['mobile'];
                $order->address_detail = $address['full_address'];
            }

            //运费
            if ($order->order_type == 1) {
                $order->freight = 0;
            } else {
                $order->freight = ConfigService::getConfigValue('freight');
            }
            //计算订单总额
            $price = GoodsSkuModel::where('id', $goods_sku_id)->value('sell_price');
            $order->total_amount = bcmul($price, $num, 2);

            $couponAmount = 0.00;
            if ($order->coupon_id) {
                //计算优惠卷优惠金额
                $couponAmount = OrderService::checkUserCoupon($order->coupon_id, $order->total_amount, $goods_id);
                $order->discount_amount = $couponAmount;
                $order->pay_amount = $order->total_amount + $order->freight - $order->discount_amount;
            } else {
                //计算等级优惠
                $preferential = UserLevelModel::where('id', $user['level_id'])->value('preferential');
                $order->grade_discount = bcmul($order->total_amount, $preferential / 100, 2);
                $order->pay_amount = $order->total_amount + $order->freight - $order->grade_discount;
            }
            $order->user_id = $this->request->userId;
            $order->order_status = 1;
            $order->effective_purchase = $goods['effective_purchase'];
            $order->green_scores = bcsub($goods['green_scores'],$num,2);
            $order->save();
            if ($type == 1) {
                OrderDetailModel::create([
                    'order_sn' => $orderSn,
                    'goods_id' => $goods_id,
                    'goods_name' => $goods['name'],
                    'goods_sku_id' => $goods_sku_id,
                    'goods_price' => $goods_sku['sell_price'],
                    'num' => $num,
                    'goods_image' => $goods['image'],
                    'goods_banner' => $goods['banner'],
                    'goods_detail' => $goods['detail'],
                    'reward_points' => $goods['reward_points'],
                    'green_scores' => $goods['green_scores'],
                    'effective_purchase' => $goods['effective_purchase'],
                ]);
            } else {
                OrderDetailModel::create([
                    'order_sn' => $orderSn,
                    'goods_id' => $pointsmall_id,
                    'goods_name' => $goods['name'],
                    'goods_sku_id' => '',
                    'goods_price' => $goods['integral'],
                    'num' => $num,
                    'goods_image' => $goods['image'],
                ]);
            }
            Db::commit();
            return $this->success(['order_sn' => $orderSn]);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function createOrderQrcode()
    {
        Db::startTrans();
        try {
            $orderSn = $this->request->param('order_sn');
            $order = OrderModel::where(['order_sn' => $orderSn, 'user_id' => $this->request->userId])->find();
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            if ($order['order_type'] != 1) {
                throw new \Exception('订单类型有误');
            }
            if ($order['qrcode']) {
                return $this->success(['qrcode' => $order['qrcode']]);
            }
            $order->qrcode = QrcodeService::createUserQrcode($order['order_sn'], $order['id']);
            $order->save();
            Db::commit();
            return $this->success(['qrcode' => $order->qrcode]);
        } catch (\Exception $exception) {
            Db::rollback();
            Log::error($exception->getMessage());
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 确认收货
     * @return \think\response\Json
     */
    public function confirmReceipt()
    {
        Db::startTrans();
        try {
            $orderSn = $this->request->param('order_sn');
            $userid = $this->request->userId;
//            $userid = 547;
            $order = OrderModel::where(['order_sn' => $orderSn, 'user_id' => $userid])->find();
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            if ($order['order_status'] != 3) {
                throw new \Exception('订单状态有误');
            }

            $order->order_status = 4;
            $order->update_time = time();
            $order->save();

            //修改用户信息
            OrderService::completeOrder($orderSn);
            Db::rollback();
            //Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            Log::error($exception->getMessage());
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 购物车下单
     * @return \think\response\Json
     */
    public function cartBuyOrder()
    {
        Db::startTrans();
        try {
            $cardIdArr = json_decode($this->request->param('goods_cart_id'), true);
            $addressId = $this->request->param('address_id');
            $pay_type = $this->request->param('pay_type');
            $order_type = $this->request->param('order_type');
            $shop_id = $this->request->param('shop_id');
            $delivery_time = $this->request->param('delivery_time');

            $userId = $this->request->userId;
//            $cardIdArr = explode(',', $cardIds);
            if (!is_array($cardIdArr)) {
                throw new \Exception('参数错误');
            }

            $orderDetailData = [];
            $totalPrice = 0;
            $orderSn = createOrderSn();
            $goodsInfoArr = [];

            foreach ($cardIdArr as $key => $cid) {
                $cartInfo = GoodsCartModel::find($cid);
                if (!$cartInfo) {
                    throw new \Exception("购物车商品不存在");
                }
                if ($userId != $cartInfo['user_id']) {
                    throw new \Exception("非法请求");
                }
                $goodsNum = $cartInfo['num'] ?? 0;
                if ($goodsNum <= 0) {
                    throw new \Exception("购买商品数量错误");
                }
                $goodsId = $cartInfo['goods_id'] ?? 0;
                $goodsInfo = GoodsModel::find($goodsId);
                if (!$goodsInfo) {
                    throw new \Exception("商品不存在");
                }
                if ($goodsInfo['status'] != 1) {
                    throw new \Exception("商品已下架");
                }
                if ($goodsInfo['stock'] <= 0) {
                    throw new \Exception("商品库存不足");
                }
                $skuInfo = GoodsSkuModel::where('id', $cartInfo['goods_sku_id'])->find();
                if ($skuInfo['stock'] <= 0) {
                    throw new \Exception("商品规格库存不足");
                }
                $orderDetailData[$key] = [
                    'order_sn' => $orderSn,
                    'goods_sku_id' => $cartInfo['goods_sku_id'],
                    'goods_id' => $goodsId,
                    'goods_name' => $goodsInfo['name'],
                    'goods_price' => $skuInfo['sell_price'],
                    'goods_image' => $goodsInfo['image'],
                    'goods_banner' => $goodsInfo['banner'],
                    'goods_detail' => $goodsInfo['detail'],
                    'num' => $goodsNum,
                ];
                $goodsTotalPrice = bcmul($skuInfo['sell_price'], $goodsNum, 2);
                $totalPrice = bcadd($totalPrice, $goodsTotalPrice, 2);
                array_push($goodsInfoArr, $goodsInfo['goods_name'] . '(规格：' . $skuInfo['name'] . $skuInfo['sell_price'] . ')*' . $goodsNum);
            }
            $deliveryFee = ConfigService::getConfigValue('freight');
            $totalPrice = $totalPrice + $deliveryFee;

            // 创建订单
            $orderModel = new OrderModel();
            $orderModel->user_id = $userId;
            $orderModel->order_sn = $orderSn;
            $orderModel->delivery_fee = $deliveryFee;
            $orderModel->total_price = $totalPrice;
            $orderModel->sell_price = $totalPrice;
//            $orderModel->remark = $remark;
            $orderModel->remark = implode(',', $goodsInfoArr);
            $orderModel->order_type = $order_type;
            if ($order_type == 1) {
                $orderModel->shop_id = $shop_id;
                $shop = ShopModel::find($orderModel->shop_id);
                if (!$shop) {
                    throw new \Exception('店铺不存在');
                }
            } else {
                $orderModel->address_id = $addressId;
                $address = UserAddressModel::where('id', $orderModel->address_id)->find();
                if (!$orderModel->address_id) {
                    throw new \Exception('地址不存在');
                }
                $orderModel->delivery_time = $this->request->param('delivery_time');
                $orderModel->username = $address['username'];
                $orderModel->user_mobile = $address['mobile'];
                $orderModel->address_detail = $address['full_address'];
            }
            $orderModel->save();
            $orderDetailModel = new OrderDetailModel();
            $orderDetailModel->saveAll($orderDetailData);
            //删除购物车
            GoodsCartModel::destroy($cardIdArr);
            Db::commit();
            return $this->success($orderSn);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 订单评价
     *
     * @return \think\response\Json
     */
    public function submitEvaluation()
    {
        Db::startTrans();
        try{
            $userId = $this->request->userId;
            $order_sn = $this->request->param('order_sn');
            $evaluation = $this->request->param('evaluation');  //评论

            $userId = '486';
            $order_sn = 'O2024052315281939566';
            $evaluation = '2222';

            $orderinfo = OrderModel::where('user_id',$userId)->where('order_sn',$order_sn)->where('order_status',4)->find()->toArray();

            if(!$orderinfo){
                throw new \Exception('订单未找到');
            }

            $evaluation_info = OrderEvaluationModel::where('order_id',$orderinfo['id'])->where('user_id',$userId)->find();

            if($evaluation_info){
                $evaluation_info->evaluation = $evaluation;
                $evaluation_info->update_time = time();
                $evaluation_info->save();
            }else{
                $goods_ids = Db::name('order_detail')->where('order_sn',$order_sn)->column('goods_id');


                OrderEvaluationModel::create([
                    'order_id' => $orderinfo['id'],
                    'user_id' => $userId,
                    'shop_id' => $orderinfo['shop_id'],
                    'goods_ids' => implode(',',$goods_ids),
                    'evaluation' => $evaluation,
                    'create_time' => time(),
                ]);

                OrderModel::where('id',$orderinfo['id'])->update(['order_status' => 5,'is_evaluation' => 1]);
            }
            Db::commit();
            return $this->success();
        }catch(\Exception $exception){
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 购物车商品下单
     */
    public function setCartOrder()
    {
        Db::startTrans();
        try {
            $cartIds = $this->request->param('cart_ids');
            $userId = $this->request->userId;
            //$userId = 451;
            $count = GoodsCartModel::whereIn('id', $cartIds)->where('user_id', $userId)->count();
            if(is_string($cartIds)){
                $cartIds = explode(',',$cartIds);
            }
            if (is_array($cartIds) && $count != count($cartIds)) {
                throw new \Exception("非法请求");
            }

            $cartGoods = GoodsCartModel::whereIn('id', $cartIds)->where('user_id', $userId)->select()->toArray();

            $address = UserAddressModel::where('user_id', $userId)->where('is_default',1)->find();

            //运费
            $freight = ConfigService::getConfigValue('freight');

            $shop_goods = [];

            foreach($cartGoods as $key => $value){
                $goods = GoodsModel::find($value['goods_id'])->toArray();
                if (!$goods) {
                    throw new \Exception('商品不存在');
                }
                if ($goods['status'] != 1) {
                    throw new \Exception('商品已下架');
                }
                $goods_sku = GoodsSkuModel::find($value['goods_sku_id'])->toArray();
                if (!$goods_sku) {
                    throw new \Exception('规格不存在');
                }
                $shop_id = intval($goods['shop_id']);
                $shop_goods[$shop_id][] = ['goods' => $goods,'sku' => $goods_sku,'num' => $value['num']];
            }

            $orderSnAry = [];
            foreach($shop_goods as $key => $value){
                $orderSn = createOrderSn();

                $effective_purchase = 0;
                $order_detail = [];
                $green_scores = 0;
                $total_amount = 0;
                foreach($value as $item){
                    if($item['goods']['effective_purchase'] == 1){
                        $effective_purchase = 1;
                    }
                    $order_detail[] = [
                        'order_sn' => $orderSn,
                        'goods_id' => $item['goods']['id'],
                        'goods_name' => $item['goods']['name'],
                        'goods_sku_id' => $item['sku']['id'],
                        'goods_price' => $item['sku']['sell_price'],
                        'num' => $item['num'],
                        'goods_image' => $item['goods']['image'],
                        'create_time' => time(),
                        'green_scores' => bcmul($goods['green_scores'],$item['num'],2),
                        'effective_purchase' => $effective_purchase
                    ];
                    $green_scores = bcadd($green_scores,bcmul($goods['green_scores'],$item['num'],2),2);
                    $total_amount = bcadd($total_amount,bcmul($item['sku']['sell_price'],$item['num'],2),2);
                }

                $order_data = [
                    'order_sn' => $orderSn,
                    'type' => 1,
                    'coupon_id' => 1,
                    'pay_type' => 1,
                    'order_type' => 2,
                    'address_id' => 0,
                    'freight' => $freight,
                    'user_id' => $userId,
                    'order_status' => 1,
                    'effective_purchase' => $effective_purchase,
                    'green_scores' => $green_scores,
                    'total_amount' => $total_amount,
                    'pay_amount' => $total_amount + $freight,
                    'shop_id' => $key,
                    'create_time' => time()
                ];
                if(!empty($address)){
                    $order_data['username'] = $address['username'];
                    $order_data['user_mobile'] = $address['user_mobile'];
                    $order_data['address_detail'] = $address['full_address'];
                    $order_data['address_id'] = $address['address_id'];
                }
                Db::name('order')->insert($order_data);
                foreach($order_detail as $detail){
                    OrderDetailModel::create($detail);
                }
                $orderSnAry[] = $orderSn;
            }
            GoodsCartModel::destroy($cartIds);
            Db::commit();
            return $this->success(['order_sn' => $orderSn,'orderSnAry'=> $orderSnAry]);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 确认订单
     */
    public function confirmOrder()
    {
        Db::startTrans();
        try {
            $orderSn = $this->request->param('orderSn');
            $orderSnAry = $this->request->param('orderSnAry');
            $where[] = ['is_del', '=', 0];
            $where[] = ['user_id', '=', $this->request->userId];
            if($orderSnAry){
                $where[] = ['order_sn', 'in', $orderSnAry];
            }else{
                $where[] = ['order_sn', '=', $orderSn];
            }

            $data = OrderModel::where($where)
                ->field('id,type,order_sn,pay_type,total_amount,shop_id,address_id,order_type,pay_amount,create_time,delivery_time,grade_discount,coupon_amount,freight,order_status,is_evaluation')
                ->order('id', 'desc')
                ->select()
                ->toArray();
            if (!$data) {
                throw new \Exception('订单不存在');
            }


            $address = UserAddressModel::where('user_id', $this->request->userId)->where('is_default',1)->find();
            $freight = 0;
            $total_amount = 0;

            foreach($data as $key => &$value){

                $freight = bcadd($freight,$value['freight'],2); //运费
                $total_amount = bcadd($total_amount,$value['total_amount'],2); //商品总价

                if(intval($value['shop_id']) == 0){
                    $value['shop_name'] = '自营';
                    $value['shop_img'] = ConfigService::getConfigValue('logo');;
                }else{
                    $shop_info = ShopModel::where('id', $value['shop_id'])->find();
                    $value['shop_name'] = $shop_info['shop_name'];
                    $value['shop_img'] = $shop_info['img'];
                }

                $value['detail'] = OrderDetailModel::where('order_sn', $value['order_sn'])
                    ->field('id,goods_sku_id,goods_name,goods_price,goods_image,num')
                    ->select()
                    ->each(function ($item) {
                        $item['goods_sku_name'] = GoodsSkuModel::where('id', $item['goods_sku_id'])->value('name');
                        return $item;
                    });
            }
            $pay_amount = bcadd($total_amount,$freight,2);

            return $this->success(['freight' => $freight,'total_amount' => $total_amount,'pay_amount' => $pay_amount,'address' => $address,'order'=> $data]);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 确认商品订单，未创建订单
     */
    public function confirmOrder2()
    {
        try {
            $cartIds = $this->request->param('cart_ids');
            $goods_id = $this->request->param('goods_id');
            $goods_sku_id = $this->request->param('goods_sku_id');
            $num = $this->request->param('num');
            $userId = $this->request->userId;

            //用户默认收货地址
            $address = UserAddressModel::where('user_id', $userId)->where('is_default',1)->find();

            //运费
            $freight = ConfigService::getConfigValue('freight');

            if(empty($cartIds)){
                $shop_info = ['shop_name' => ConfigService::getConfigValue('shop_name'),'shop_img' => ConfigService::getConfigValue('shop_logo')];
                //直接下单
                $data = [
                    "total_amount" => 0,
                    "green_scores" => 0,
                    "address" => $address,
                    "total_freight" => $freight,
                    'data' => [],//['shop' => ['shop_name' => $shop_info['shop_name'],'shop_img' => $shop_info['shop_img']],'list' => []]
                ];

                $goods = GoodsModel::find($goods_id)->toArray();
                if (!$goods) {
                    throw new \Exception('商品不存在');
                }
                if ($goods['status'] != 1) {
                    throw new \Exception('商品已下架');
                }
                $goods_sku = GoodsSkuModel::find($goods_sku_id)->toArray();
                if (!$goods_sku) {
                    throw new \Exception('规格不存在');
                }
                $shop_id = intval($goods['shop_id']);
                if($shop_id != 0){
                    $shop_info = ShopModel::where('id', $goods['shop_id'])->find();
                }
                $data['data'] = [
                    [
                        'shop' => ['shop_name' => $shop_info['shop_name'],'shop_img' => $shop_info['shop_img']],
                        'list' => []
                    ]
                ];
                //['shop'] = ['shop_name' => $shop_info['shop_name'],'shop_img' => $shop_info['shop_img']];
                $data['data'][0]['list'][] = ['goods' => $goods,'sku' => $goods_sku,'num' => $num];

                $data['total_amount'] = bcmul($goods_sku['sell_price'],$num,2);
                $data['green_scores'] = bcmul($goods['green_scores'],$num,2);
                $data['total_num'] = $num;

                $pay_amount = bcadd($data['total_amount'],$data['total_freight'],2);

                $data['pay_data'] = OrderService::payType($pay_amount,$data['green_scores'],$userId);

                return $this->success($data);
            }else{
                //购物车下单
                $cartGoods = GoodsCartModel::whereIn('id', $cartIds)->where('user_id', $userId)->select()->toArray();

                $shop_goods = [];

                foreach($cartGoods as $key => $value){
                    $goods = GoodsModel::find($value['goods_id'])->toArray();
                    if (!$goods) {
                        throw new \Exception('商品不存在');
                    }
                    if ($goods['status'] != 1) {
                        throw new \Exception('商品已下架');
                    }
                    $goods_sku = GoodsSkuModel::find($value['goods_sku_id'])->toArray();
                    if (!$goods_sku) {
                        throw new \Exception('规格不存在');
                    }
                    $shop_id = intval($goods['shop_id']);
                    if(!isset($shop_goods[$shop_id])){
                        if($shop_id == 0){
                            $shop_info = ['shop_name' => '自营','shop_img' => ConfigService::getConfigValue('logo')];
                        }else{
                            $shop_info = ShopModel::where('id', $value['shop_id'])->find();
                        }
                        $shop_goods[$shop_id]['shop'] = $shop_info;
                        $shop_goods[$shop_id]['list'] = [];
                    }

                    $shop_goods[$shop_id]['list'][] = ['goods' => $goods,'sku' => $goods_sku,'num' => $value['num']];
                }

                $green_scores = 0;
                $total_amount = 0;
                $total_freight = 0;
                $total_num = 0;
                foreach($shop_goods as $key => $value){
                    $total_freight = bcadd($freight,$total_freight,2);
                    foreach($value['list'] as $item){
                        $green_scores = bcadd($green_scores,bcmul($goods['green_scores'],$item['num'],2),2);
                        $total_amount = bcadd($total_amount,bcmul($item['sku']['sell_price'],$item['num'],2),2);
                        $total_num += $item['num'];
                    }

                }
                $pay_amount = bcadd($total_amount,$total_freight,2);

                $data = [
                    'data' => $shop_goods,
                    'total_amount'=> $total_amount,
                    'green_scores' => $green_scores,
                    'address' => $address,
                    'total_freight' => $total_freight,
                    'total_num' => $total_num,
                    'cartIds' => $cartIds,
                    'pay_data' => OrderService::payType($pay_amount,$green_scores,$userId)
                ];
                return $this->success($data);
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 创建订单
     * @return \think\response\Json
     */
    public function createOrder2()
    {
        Db::startTrans();
        try {
            $cartIds = $this->request->param('cart_ids');
            $goods_id = $this->request->param('goods_id');
            $goods_sku_id = $this->request->param('goods_sku_id');
            $num = $this->request->param('num');
            $address_id = $this->request->param('address_id');
            $pay_type = $this->request->param('pay_type');
            $userId = $this->request->userId;
            //用户默认收货地址
            $address = UserAddressModel::where('user_id', $userId)->where('id',$address_id)->find();

            //运费
            $freight = ConfigService::getConfigValue('freight');

            if(empty($cartIds)){
                $shop_info = ['shop_name' => ConfigService::getConfigValue('shop_name'),'shop_img' => ConfigService::getConfigValue('shop_logo')];
                //直接下单

                $goods = GoodsModel::find($goods_id)->toArray();
                if (!$goods) {
                    throw new \Exception('商品不存在');
                }
                if ($goods['status'] != 1) {
                    throw new \Exception('商品已下架');
                }
                $goods_sku = GoodsSkuModel::find($goods_sku_id)->toArray();
                if (!$goods_sku) {
                    throw new \Exception('规格不存在');
                }
                if ($goods_sku['stock'] < $num) {
                    throw new \Exception('商品库存不足');
                }
                $shop_id = intval($goods['shop_id']);
                if($shop_id != 0){
                    $shop_info = ShopModel::where('id', $goods['shop_id'])->find();
                }
                $data = [
                    [
                        'shop' => ['shop_name' => $shop_info['shop_name'],'shop_img' => $shop_info['shop_img']],
                        'list' => []
                    ]
                ];
                $data[0]['list'][] = ['goods' => $goods,'sku' => $goods_sku,'num' => $num];
                $shop_goods = $data;
            }else{
                //购物车下单
                $cartGoods = GoodsCartModel::whereIn('id', $cartIds)->where('user_id', $userId)->order('create_time desc')->select()->toArray();

                $shop_goods = [];

                foreach($cartGoods as $key => $value){
                    $goods = GoodsModel::find($value['goods_id'])->toArray();
                    if (!$goods) {
                        throw new \Exception('商品不存在');
                    }
                    if ($goods['status'] != 1) {
                        throw new \Exception('商品已下架');
                    }
                    $goods_sku = GoodsSkuModel::find($value['goods_sku_id'])->toArray();
                    if (!$goods_sku) {
                        throw new \Exception('规格不存在');
                    }
                    if ($goods_sku['stock'] < $value['num']) {
                        throw new \Exception('商品库存不足');
                    }
                    $shop_id = intval($goods['shop_id']);
                    if(!isset($shop_goods[$shop_id])){
                        if($shop_id == 0){
                            $shop_info = ['shop_name' => '自营','shop_img' => ConfigService::getConfigValue('logo')];
                        }else{
                            $shop_info = ShopModel::where('id', $value['shop_id'])->find();
                        }
                        $shop_goods[$shop_id]['shop'] = $shop_info;
                        $shop_goods[$shop_id]['list'] = [];
                    }

                    $shop_goods[$shop_id]['list'][] = ['goods' => $goods,'sku' => $goods_sku,'num' => $value['num']];
                }

                $green_scores = 0;
                $total_amount = 0;
                $total_freight = 0;
                foreach($shop_goods as $key => $value){
                    $total_freight = bcadd($freight,$total_freight,2);
                    foreach($value['list'] as $item){
                        $green_scores = bcadd($green_scores,bcmul($goods['green_scores'],$item['num'],2),2);
                        $total_amount = bcadd($total_amount,bcmul($item['sku']['sell_price'],$item['num'],2),2);
                    }
                }
            }

            //统一支付订单
            $union_order_sn = createOrderSn();

            //创建订单
            $orderSnAry = [];
            foreach($shop_goods as $key => $value){
                $orderSn = createOrderSn();
                $effective_purchase = 0;
                $order_detail = [];
                $green_scores = 0;
                $total_amount = 0;
                $label = 0;

                foreach($value['list'] as $item){
                    if($item['goods']['effective_purchase'] == 1){
                        $effective_purchase = 1;
                    }
                    $order_detail[] = [
                        'order_sn' => $orderSn,
                        'goods_id' => $item['goods']['id'],
                        'goods_name' => $item['goods']['name'],
                        'goods_sku_id' => $item['sku']['id'],
                        'goods_price' => $item['sku']['sell_price'],
                        'num' => $item['num'],
                        'goods_image' => $item['goods']['image'],
                        'create_time' => time(),
                        'green_scores' => bcmul($item['goods']['green_scores'],$item['num'],2),
                        'effective_purchase' => $effective_purchase
                    ];
                    $green_scores = bcadd($green_scores,bcmul($item['goods']['green_scores'],$item['num'],2),2);
                    $total_amount = bcadd($total_amount,bcmul($item['sku']['sell_price'],$item['num'],2),2);
                    $label = $item['goods']['label'];
                }

                $order_data = [
                    'order_sn' => $orderSn,
                    'type' => 1,
                    'coupon_id' => 1,
                    'pay_type' => $pay_type,
                    'order_type' => 2,
                    'address_id' => 0,
                    'freight' => $freight,
                    'user_id' => $userId,
                    'order_status' => 1,
                    'effective_purchase' => $effective_purchase,
                    'green_scores' => $green_scores,
                    'total_amount' => $total_amount,
                    'pay_amount' => $total_amount + $freight,
                    'shop_id' => $key,
                    'create_time' => time(),
                    'union_order_sn' => $union_order_sn,
                    'label' => $label
                ];
                $pay_data = OrderService::payType($order_data['pay_amount'],$green_scores,$userId);
                $order_data['order_integral'] = $pay_data['order_integral'];//支付消费积分
                $order_data['order_balance'] = $pay_data['order_balance']; //支付消费余额

                if(!empty($address)){
                    $order_data['username'] = $address['username'];
                    $order_data['user_mobile'] = $address['mobile'];
                    $order_data['address_detail'] = $address['full_address'];
                    $order_data['address_id'] = $address['id'];
                }
                OrderModel::create($order_data);

                foreach($order_detail as $detail){
                    OrderDetailModel::create($detail);

                    //商品库存清除
                    GoodsService::setStock($detail['goods_sku_id'],$detail['num']);
                }
                $orderSnAry[] = $orderSn;
            }
            if(!empty($cartIds)){
                GoodsCartModel::destroy($cartIds);
            }
            Db::commit();
            return $this->success(['order_sn' => $orderSn,'orderSnAry'=> $orderSnAry]);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 售后
     * @return void
     */
    public function after_sales()
    {
        try {
            $id = $this->request->param('order_id');
            $after_sales_type = $this->request->param('after_sales_type');
            $after_sales_reason = $this->request->param('after_sales_reason');
            $order = OrderModel::find($id);
            if(!$order){
                throw new \Exception('订单不存在！');
            }
            if(in_array($order['order_status'],[0,1,2])){
                throw new \Exception('当前状态无法取消订单！');
            }

            if($order['order_status'] == 7){
                throw new \Exception('当前订单订单正在售后！');
            }

            OrderModel::where(['id' => $id, 'user_id' => $this->request->userId])->update([
                'order_status' => 7,
                'after_sales_type'=> $after_sales_type,
                'after_sales_time' => time(),
                'after_sales_status' => $order['order_status'],
                'after_sales_reason' => $after_sales_reason
            ]);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 订单列表
     * @return \think\response\Json
     */
    public function getAfterSalesList()
    {
        try {
            $where = [];
            $where[] = ['is_del', '=', 0];
            $userId = $this->request->userId;
            $page = $this->page;
            $limit = $this->limit;
            $where[] = ['user_id', '=', $userId];
            $where[] = ['order_status', 'in', [7,8]];

            //获取收货电话
            $after_sales_mobile = ConfigService::getConfigValue('after_sales_mobile');

            $list = OrderModel::where($where)
                ->field('id,type,order_sn,order_type,pay_type,pay_amount,create_time,order_status,after_sales_type,after_sales_time,after_sales_status,refund_type')
                ->order('id', 'desc')
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->each(function ($item) use ($after_sales_mobile) {
                    $item['detail'] = OrderDetailModel::where('order_sn', $item['order_sn'])->field('id,goods_name,goods_price,goods_image,num')->select();

                    if($item['shop'] == 0){
                        $item['shop_name'] = ConfigService::getConfigValue('shop_name');
                        $item['shop_img'] = ConfigService::getConfigValue('shop_logo');
                    }else{
                        $shopinfo = ShopModel::where('id', $item['shop_id'])->find();
                        $item['shop_name'] = $shopinfo['shop_name'];
                        $item['shop_img'] = $shopinfo['img'];
                    }
                    $item['after_sales_mobile'] = $after_sales_mobile;
                    return $item;
                })->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


}